package com.easymin.weixin.controller.v5;

import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nl.captcha.backgrounds.SquigglesBackgroundProducer;
import nl.captcha.backgrounds.TransparentBackgroundProducer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.easymin.weixin.common.IpHelper;

import nl.captcha.Captcha;
import nl.captcha.backgrounds.GradiatedBackgroundProducer;
import nl.captcha.gimpy.BlockGimpyRenderer;
import nl.captcha.noise.CurvedLineNoiseProducer;
import nl.captcha.noise.NoiseProducer;
import nl.captcha.text.producer.DefaultTextProducer;
import nl.captcha.text.producer.TextProducer;
import nl.captcha.text.renderer.DefaultWordRenderer;
import nl.captcha.text.renderer.WordRenderer;

@Controller
@RequestMapping("v5/captcha")
public class CaptchaController {

	private static Pattern PATTERN = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$");


	@RequestMapping("/code")
	public void getImageVCode (HttpServletRequest request, HttpServletResponse response) throws IOException {

		/*
		 * 获取前台传入的标记值，主要是为了区分这个验证码是谁的
		 * 以便于验证时取出该验证码，当没有传入时或传入的格式不正确，我们认为这是入侵，直接返回
		 */
		String phone = request.getParameter("p");
		
		if (null == phone || phone.isEmpty()) {
			return;
		}

		Matcher m = PATTERN.matcher(phone);
		
		if (!m.matches()) {
			return;
		}

		Captcha.Builder builder = new Captcha.Builder(100, 37);

		// 增加边框
		builder.addBorder();
		NoiseProducer nProd = new CurvedLineNoiseProducer(Color.BLACK, 2);

		// 增加干扰线条
		builder.addNoise(nProd);

		// ----------------自定义字体大小-----------
		// 自定义设置字体颜色和大小 最简单的效果 多种字体随机显示
		List<Font> fontList = new ArrayList<Font>();
		fontList.add(new Font("Courier", Font.ITALIC, 30));

		// 加入多种颜色后会随机显示 字体空心
		List<Color> colorList = new ArrayList<Color>();
		colorList.add(Color.BLACK);
		DefaultWordRenderer cwr = new DefaultWordRenderer(colorList, fontList);
		// ColoredEdgesWordRenderer cwr= new
		// ColoredEdgesWordRenderer(colorList,fontList);

		WordRenderer wr = cwr;
		// 增加文本，默认为5个随机字符.
		// builder.addText();


		char[] numberChar = new char[] {
				'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a','b','c','d','e','f','g','h','i','j','k','l','m','n' };
		TextProducer text = new DefaultTextProducer(4, numberChar);
		builder.addText(text, wr);

		// --------------添加背景-------------
		// 设置背景渐进效果 以及颜色 form为开始颜色，to为结束颜色
		GradiatedBackgroundProducer gbp = new GradiatedBackgroundProducer();
		gbp.setFromColor(Color.WHITE);
		gbp.setToColor(Color.WHITE);


		// 无渐进效果，只是填充背景颜色
		// FlatColorBackgroundProducer fbp=new
		// FlatColorBackgroundProducer(Color.white);
		// 加入网纹--一般不会用
		SquigglesBackgroundProducer sbp=new SquigglesBackgroundProducer();

		// 没发现有什么用,可能就是默认的
		TransparentBackgroundProducer tbp = new TransparentBackgroundProducer();

		builder.addBackground(gbp);
		builder.addBackground(sbp);
		builder.addBackground(tbp);

		// ---------装饰字体---------------
		// 字体边框齿轮效果 默认是3
		builder.gimp(new BlockGimpyRenderer(1));
		// 波纹渲染 相当于加粗
		// builder.gimp(new RippleGimpyRenderer());
		// 加网--第一个参数是横线颜色，第二个参数是竖线颜色
		// builder.gimp(new FishEyeGimpyRenderer(Color.white,Color.black));
		// 加入阴影效果 默认3，75
		// builder.gimp(new DropShadowGimpyRenderer(3, 75));

		Captcha captcha = builder.build();
		String code = captcha.getAnswer();
		String IP = IpHelper.getIp(request);
		HttpSession session = request.getSession();
		session.setAttribute("captcha_" + IP.replaceAll(".", "_") + "_" + phone , code);
		session.setMaxInactiveInterval(60);

		BufferedImage bi = captcha.getImage(); // captchaService.getCaptcha(captchaId);
		StringBuilder sb2 = new StringBuilder();
		sb2.append("yB").append("-").append("de").append("rew").append("oP").reverse();
		StringBuilder sb = new StringBuilder();
		sb.append("moc.").append("nim").append("ys").append("ae").reverse();

		response.addHeader(sb2.toString(), sb.toString());
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0L);
		response.setContentType("image/jpeg");

		OutputStream os = null;
		os = response.getOutputStream();
		ImageIO.write(bi, "jpg", os);
		os.flush();
	}
}
